package com.hyzh.latte.vehicle.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.coffee.core.CoffeeResponse;
import com.hyzh.latte.util.LatteResponseCode;
import com.hyzh.latte.util.StringKits;
import com.hyzh.latte.util.gather.OkhttpUtil;
import com.hyzh.latte.vehicle.dmo.*;
import com.hyzh.latte.vehicle.dmo.entity.ParkPGEntity;
import com.hyzh.latte.vehicle.dmo.entity.PolePGEntity;
import com.hyzh.latte.vehicle.dmo.entity.VehicleTrackRecordPGEntity;
import com.hyzh.latte.vehicle.nezha.NezhaDeviceManager;
import com.hyzh.latte.vehicle.nezha.NezhaPersonManager;
import com.hyzh.latte.vehicle.nezha.PoleEdge;
import com.hyzh.latte.vehicle.nezha.PoleVertex;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.hutool.json.XMLTokener.entity;

/**
 * @author songkui
 * @since 2024/5/19 15:52
 */
@Service
@Slf4j
@AllArgsConstructor
public class VehicleTrackService {

    private final NezhaRecordService nezhaRecordService;

    public CoffeeResponse<List<VehiclePathMessage>> historyTrackOnline(LocalDateTime startTime, LocalDateTime endTime, String park, String vno) {
        List<VehicleTrackRecordPGEntity> list = nezhaRecordService.listTrackRecord(park, vno, startTime, endTime);
        if (CollectionUtil.isEmpty(list) || list.size() < 2) {
            log.error("vehicleTrack: history data is null, vno: {}", vno);
            return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
        }

//        Set<Integer> dictSet = list.stream().map(VehicleTrackRecordPGEntity::getDit).collect(Collectors.toSet());
//        if (CollectionUtil.isEmpty(dictSet) || dictSet.size() < 2) {
//            log.error("vehicleTrack: history data gate size < 2, vno: {}", vno);
//            return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
//        }


        List<VehiclePathMessage> dataList = new ArrayList<>();
        int size = list.size();
        if (size < 3) {
            VehiclePathMessage message = buildPathMessageOnline(park, vno, list);
            if (null == message) {
                return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
            }
            dataList.add(message);
            return CoffeeResponse.responseSuccess(dataList);
        }

        // size > 2
        List<VehicleTrackRecordPGEntity> temp = new ArrayList<>();
        boolean isTrack = false;
        for (int i = 0; i < size - 1; i++) {
            VehicleTrackRecordPGEntity current = list.get(i);
            listAdd(temp, current);
            VehicleTrackRecordPGEntity next = list.get(i + 1);
            listAdd(temp, next);
            isTrack = false;
            if (-9 == next.getDit() || 8 == next.getDit()) {
                ++i;
                VehiclePathMessage message = buildPathMessageOnline(park, vno, temp);
                if (null != message) {
                    dataList.add(message);
                }
                temp.clear();
                isTrack = true;
            }
        }

        if (!isTrack){
            VehiclePathMessage message = buildPathMessageOnline(park, vno, temp);
            if (null != message) {
                dataList.add(message);
            }
        }

        if (CollectionUtil.isEmpty(dataList)) {
            return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
        }

        VehiclePathMessage pathMessage = dataList.get(dataList.size() -1);
        if (pathMessage.getPoint() ==1 && pathMessage.getGate() == -9 && dataList.size() > 1){
            pathMessage = dataList.get(dataList.size() -2);
        }

        List<VehiclePathMessage> resList = new ArrayList<>(1);
        resList.add(pathMessage);
        return CoffeeResponse.responseSuccess(resList);

    }
    public CoffeeResponse<List<VehiclePathMessage>> historyTrack(LocalDateTime startTime, LocalDateTime endTime, String park, String vno) {
        List<VehicleTrackRecordPGEntity> list = nezhaRecordService.listTrackRecord(park, vno, startTime, endTime);
        if (CollectionUtil.isEmpty(list) || list.size() < 2) {
            log.error("vehicleTrack: history data is null, vno: {}", vno);
            return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
        }

        list = list.stream().filter(x -> null != NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, x.getPoleCode(), x.getPoleLab()) ).collect(Collectors.toList());

        Set<Integer> dictSet = list.stream().map(VehicleTrackRecordPGEntity::getDit).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(dictSet) || dictSet.size() < 2) {
            log.error("vehicleTrack: history data gate size < 2, vno: {}", vno);
            return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
        }


        List<VehiclePathMessage> dataList = new ArrayList<>();
        int size = list.size();
        if (size < 3) {
            VehiclePathMessage message = buildPathMessage(park, vno, list);
            if (null == message) {
                return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
            }
            dataList.add(message);
            return CoffeeResponse.responseSuccess(dataList);
        }

        // size > 2
        List<VehicleTrackRecordPGEntity> temp = new ArrayList<>();
        for (int i = 0; i < size - 1; i++) {
            VehicleTrackRecordPGEntity current = list.get(i);
            listAdd(temp, current);
            VehicleTrackRecordPGEntity next = list.get(i + 1);
            listAdd(temp, next);
            if (-9 == next.getDit() || 8 == next.getDit()) {
                ++i;
                VehiclePathMessage message = buildPathMessage(park, vno, temp);
                if (null != message) {
                    dataList.add(message);
                }
                temp.clear();
            }
        }

        if (CollectionUtil.isEmpty(dataList)) {
            return CoffeeResponse.response(LatteResponseCode.ExcelNotData);
        }

        return CoffeeResponse.responseSuccess(dataList);

    }

    @Deprecated
    public List<VehiclePathMessage> listVehicleTrack(String park, LocalDateTime startTime, LocalDateTime endTime){
        List<VehicleTrackRecordPGEntity> list = nezhaRecordService.listVehicleTrack(park, startTime, endTime);
        if (CollectionUtil.isEmpty(list)){
            return null;
        }
        Map<String, List<VehicleTrackRecordPGEntity>> map = list.stream().collect(Collectors.groupingBy(VehicleTrackRecordPGEntity::getVehicleNo));
        List<VehiclePathMessage> data = new ArrayList<>();
        List<VehicleTrackRecordPGEntity> temp = new ArrayList<>();
        int s = RandomUtil.randomInt(40, 60);
        int ii = 0;
        for (Map.Entry<String, List<VehicleTrackRecordPGEntity>>  entry : map.entrySet()){
            if (ii > s){
                return data;
            }
            ++ii;
            //按照 出园区分组处理
            List<VehicleTrackRecordPGEntity> vl = entry.getValue();
            int size = vl.size();
            if (size > 1){
                for (VehicleTrackRecordPGEntity entity : vl) {
                    temp.add(entity);
                    if (-9 == entity.getDit() || 1 == entity.getDoType()) {
                        doListVehicleTrack(park, entry.getKey(), temp, data);
                        temp.clear();
                    }
                }
            }

        }

        return data;
    }

    public void doListVehicleTrack(String park, String vno, List<VehicleTrackRecordPGEntity> data, List<VehiclePathMessage> res){
        if (CollectionUtil.isEmpty(data) || data.size() == 1){
            return;
        }

        VehicleTrackRecordPGEntity startTrack = data.get(0);
        int size = data.size();
        VehicleBO vehicleBO = new VehicleBO();
        vehicleBO.setVehicleNo(vno);
        vehicleBO.setType(startTrack.getVehicleType());
        VehiclePathMessage message = new VehiclePathMessage();
        message.setId(System.currentTimeMillis()+RandomUtil.randomLong(99999));
        message.setVehicleId(startTrack.getObjectId());
        message.setVehicleNo(vehicleBO.getVehicleNo());
        message.setType(vehicleBO.getType());
        message.setStartTime(DateUtil.formatLocalDateTime(startTrack.getAddTime()));
        message.setEndTime(DateUtil.formatLocalDateTime(data.get(data.size()-1).getAddTime()));
        if (size == 1) {
            computePoint(message, park, startTrack);
            res.add(message);
            return;
        }
        List<PoleEdge> edgeList = new ArrayList<>();
        for (int i = 0; i < size - 1; i++) {
            VehicleTrackRecordPGEntity current = data.get(i);
            VehicleTrackRecordPGEntity next = data.get(i + 1);
            Optional.ofNullable(doPoleEdge(park, current, next)).ifPresent(edgeList::addAll);
        }
        if (CollectionUtil.isEmpty(edgeList)) {
            log.error("doListVehicleTrack: edgeList is null ; vno: {}", vno);
            return;
        }
        computeLine(message, edgeList, vehicleBO);
        res.add(message);
    }

    private void listAdd(List<VehicleTrackRecordPGEntity> temp, VehicleTrackRecordPGEntity trackRecordDTO) {
        for (VehicleTrackRecordPGEntity dto : temp) {
            if (dto.getId().equals(trackRecordDTO.getId())) {
                return;
            }
        }
        temp.add(trackRecordDTO);
    }


    private VehiclePathMessage buildPathMessageOnline(String park, String vno, List<VehicleTrackRecordPGEntity> trackList) {
        if (CollectionUtil.isEmpty(trackList)) {
            return null;
        }

        int size = trackList.size();
        VehicleTrackRecordPGEntity startTrack = trackList.stream().filter(d -> 9 == d.getDit() || -8 == d.getDit()).reduce((first, second) -> second).orElse(null);
        if (null == startTrack) {
             startTrack = trackList.get(0);
        }

        VehicleTrackRecordPGEntity endTrack = trackList.get(size - 1);
        VehicleBO vehicleBO = new VehicleBO();
        vehicleBO.setVehicleNo(vno);
        vehicleBO.setType(startTrack.getVehicleType());
        VehiclePathMessage message = new VehiclePathMessage();
        message.setId(System.currentTimeMillis()+RandomUtil.randomLong(99999));
        message.setVehicleId(startTrack.getObjectId());
        message.setVehicleNo(vehicleBO.getVehicleNo());
        message.setType(vehicleBO.getType());
        message.setStartTime(DateUtil.formatLocalDateTime(startTrack.getAddTime()));
        message.setGate(endTrack.getDit());
        Map<String, List<VehicleTrackRecordPGEntity>> map = trackList.stream().filter(x -> StrUtil.isNotEmpty(x.getPoleCode())).collect(Collectors.groupingBy(VehicleTrackRecordPGEntity::getPoleCode));
        if (size == 1  || (size == 2 && startTrack.getPoleCode().equals(endTrack.getPoleCode())) || map.size() == 1) {
            message.setEndTime(message.getStartTime());
            return computePoint(message, park, startTrack);
        }


        message.setEndTime(DateUtil.formatLocalDateTime(endTrack.getAddTime()));

        PoleVertex startPole = NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, startTrack.getPoleCode(), startTrack.getPoleLab());
        PoleVertex endPole = NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, endTrack.getPoleCode(), endTrack.getPoleLab());
        if (null == startPole || null == endPole) {
            log.error("vehicleTrack:  startPole or endPole is null  | startPole: {}_{}, endPole: {}_{} ", startTrack.getPoleCode(), startTrack.getPoleLab(), endTrack.getPoleCode(), endTrack.getPoleLab());
            return null;
        }

        //------------------
        int indexStart = trackList.indexOf(startTrack);
        if (indexStart < 0) {
            return null;
        }

        List<PoleEdge> edgeList = new ArrayList<>();
        List<VehicleTrackRecordPGEntity> oList = trackList.subList(indexStart, size);
        int sz = oList.size();
        for (int i = 0; i < sz - 1; i++) {
            VehicleTrackRecordPGEntity current = oList.get(i);
            VehicleTrackRecordPGEntity next = oList.get(i + 1);
            Optional.ofNullable(doPoleEdge(park, current, next)).ifPresent(edgeList::addAll);
        }

        if (oList.size() == 1){
            message.setEndTime(message.getStartTime());
            return computePoint(message, park, endTrack);
        }

        if (CollectionUtil.isEmpty(edgeList)) {
            log.error("vehicleTrack: vertexList not null but edgeList is null ; startPole: {}_{}, endPole: {}_{} ", startPole.getPoleCode(), startPole.getLab(), endPole.getPoleCode(), endPole.getLab());
            return null;
        }
        return computeLine(message, edgeList, vehicleBO);
    }

    private VehiclePathMessage buildPathMessage(String park, String vno, List<VehicleTrackRecordPGEntity> trackList) {
        if (CollectionUtil.isEmpty(trackList)) {
            return null;
        }

        int size = trackList.size();
        VehicleTrackRecordPGEntity startTrack = trackList.stream().filter(d -> 9 == d.getDit() || -8 == d.getDit()).reduce((first, second) -> second).orElse(null);
        if (null == startTrack) {
            log.info("vehicleTrack: start  this data not dit = 8 ");
            return null;
        }

        VehicleTrackRecordPGEntity endTrack = trackList.stream().filter(d -> -9 == d.getDit() || 8 == d.getDit()).reduce((first, second) -> second).orElse(null);
        if (null == endTrack) {
            log.info("vehicleTrack: this data not dit = -9 ");
            return null;
        }
        VehicleBO vehicleBO = new VehicleBO();
        vehicleBO.setVehicleNo(vno);
        vehicleBO.setType(startTrack.getVehicleType());
        VehiclePathMessage message = new VehiclePathMessage();
        message.setId(System.currentTimeMillis()+RandomUtil.randomLong(99999));
        message.setVehicleId(startTrack.getObjectId());
        message.setVehicleNo(vehicleBO.getVehicleNo());
        message.setType(vehicleBO.getType());
        message.setStartTime(DateUtil.formatLocalDateTime(startTrack.getAddTime()));
        message.setGate(8 == endTrack.getDit() ? 8 : 0);
        if (size == 1) {
            message.setEndTime(message.getStartTime());
            return computePoint(message, park, startTrack);
        }
        message.setEndTime(DateUtil.formatLocalDateTime(endTrack.getAddTime()));

        PoleVertex startPole = NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, startTrack.getPoleCode(), startTrack.getPoleLab());
        PoleVertex endPole = NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, endTrack.getPoleCode(), endTrack.getPoleLab());
        if (null == startPole || null == endPole) {
            log.error("vehicleTrack:  startPole or endPole is null  | startPole: {}_{}, endPole: {}_{} ", startTrack.getPoleCode(), startTrack.getPoleLab(), endTrack.getPoleCode(), endTrack.getPoleLab());
            return null;
        }

        //------------------
        int indexStart = trackList.indexOf(startTrack);
        if (indexStart < 0) {
            return null;
        }

        List<PoleEdge> edgeList = new ArrayList<>();
        List<VehicleTrackRecordPGEntity> oList = trackList.subList(indexStart, size);
        int sz = oList.size();
        for (int i = 0; i < sz - 1; i++) {
            VehicleTrackRecordPGEntity current = oList.get(i);
            VehicleTrackRecordPGEntity next = oList.get(i + 1);
            Optional.ofNullable(doPoleEdge(park, current, next)).ifPresent(edgeList::addAll);
        }
        if (CollectionUtil.isEmpty(edgeList)) {
            log.error("vehicleTrack: vertexList not null but edgeList is null ; startPole: {}_{}, endPole: {}_{} ", startPole.getPoleCode(), startPole.getLab(), endPole.getPoleCode(), endPole.getLab());
            return null;
        }
        return computeLine(message, edgeList, vehicleBO);
    }

    private List<PoleEdge> doPoleEdge(String park, VehicleTrackRecordPGEntity current, VehicleTrackRecordPGEntity next) {
        PoleVertex startPole = NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, current.getPoleCode(), current.getPoleLab());
        PoleVertex endPole = NezhaDeviceManager.getInstance().getPoleVertexByPoleCode(park, next.getPoleCode(), next.getPoleLab());
        if (null == startPole || null == endPole) {
            log.error("vehicleTrack:  startPole or endPole is null or equals | startPole: {}_{}, endPole: {}_{} ", current.getPoleCode(), current.getPoleLab(), next.getPoleCode(), next.getPoleLab());
            return null;
        }
        if (startPole.equals(endPole)){
//            PoleVertex  temp = new PoleVertex();
//            temp.setPoleCode(endPole.getPoleCode());
//            temp.setParkCode(endPole.getParkCode());
//            temp.setLab("y".equals(endPole.getLab()) ? "x" : "y");
//            endPole = temp;
            log.error("vehicleTrack:  startPole   endPole equals true: {}_{}, endPole: {}_{} ", current.getPoleCode(), current.getPoleLab(), next.getPoleCode(), next.getPoleLab());
            return null;
        }

        List<PoleVertex> vertexList = NezhaDeviceManager.getInstance().findVertexPaths(park, startPole, endPole);
        if (CollectionUtil.isEmpty(vertexList) || vertexList.size() == 1 || vertexList.size() > 300) {
            log.error("vehicleTrack:  data out of range or is null  | startPole: {}_{}, endPole: {}_{} ", startPole.getPoleCode(), startPole.getLab(), endPole.getPoleCode(), endPole.getLab());
            return null;
        }
        List<PoleEdge> edgeList = NezhaDeviceManager.getInstance().findEdgePaths(park, startPole, endPole);
        if (CollectionUtil.isEmpty(edgeList)) {
            log.error("vehicleTrack: vertexList not null but edgeList is null ; startPole: {}_{}, endPole: {}_{} ", startPole.getPoleCode(), startPole.getLab(), endPole.getPoleCode(), endPole.getLab());
            return null;
        }

        return edgeList;
    }


    private VehiclePathMessage computePoint(VehiclePathMessage pathMessage, String park, VehicleTrackRecordPGEntity track) {
        PolePGEntity pgEntity = NezhaDeviceManager.getInstance().getPolePGEntityByPoleCode(park, track.getPoleCode());
        if (null == pgEntity) {
            return null;
        }

        List<PointMessage> list = new ArrayList<>(1);
        PointMessage pointMessage = new PointMessage();
        pointMessage.setLatitude(pgEntity.getXLat());
        pointMessage.setLongitude(pgEntity.getXLon());
        pointMessage.setHeight(pgEntity.getXHeight());
        pointMessage.setActTime(0);
        list.add(pointMessage);

        pathMessage.setPoint(1);
        pathMessage.setPoints(list);
        return pathMessage;
    }

    private VehiclePathMessage computeLine(VehiclePathMessage pathMessage, List<PoleEdge> edgeList, VehicleBO vehicleBO) {
        List<PointMessage> pointList = new ArrayList<>();
        for (PoleEdge edge : edgeList) {
            List<PointBO> pointBOList = edge.getPointList();
            if (CollectionUtil.isNotEmpty(pointBOList)) {
                for (PointBO bo : pointBOList) {
                    pointList.add(bo.buildMessage(vehicleBO.buildTime(bo.getT())));
                }
            }
        }

        pathMessage.setPoint(0);
        pathMessage.setPoints(pointList);
        return pathMessage;
    }


    //轨迹经过的详细信息
    public List<VehicleTrackStreamVO> findTrackStream(LocalDateTime startTime, LocalDateTime endTime, String park, String vno) {
        List<VehicleTrackRecordPGEntity> list = nezhaRecordService.listTrackRecord(park, vno, startTime, endTime);
        if (CollectionUtil.isEmpty(list)) {
            log.error("vehicleTrack: history track stream data is null, park: {};  vno: {}", park, vno);
            return null;
        }

        for (VehicleTrackRecordPGEntity dto : list) {
            dto.setRoad(NezhaDeviceManager.getInstance().getPolePGEntityByPoleCode(park, dto.getPoleCode()).getRoad());
        }

        Map<String, List<VehicleTrackRecordPGEntity>> map = list.stream().collect(Collectors.groupingBy(VehicleTrackRecordPGEntity::getRoad));
        List<VehicleTrackStreamVO> dataList = new ArrayList<>(map.size());
        for (Map.Entry<String, List<VehicleTrackRecordPGEntity>> entry : map.entrySet()){
            dataList.add(buildStreamVO(entry.getValue()));
        }

        return dataList;

    }

    private VehicleTrackStreamVO buildStreamVO(List<VehicleTrackRecordPGEntity> list){
        if (list.size() == 1){
            VehicleTrackRecordPGEntity dto =  list.get(0);
            LocalDateTime startTime = dto.getAddTime().minusMinutes(RandomUtil.randomInt(3, 9));
            LocalDateTime endTime = dto.getAddTime().plusMinutes(RandomUtil.randomInt(5, 9));
            return VehicleTrackStreamVO.of(startTime, endTime, list);
        }

        list = list.stream().sorted(Comparator.comparing(VehicleTrackRecordPGEntity::getAddTime)).collect(Collectors.toList());
        LocalDateTime startTime = list.get(0).getAddTime();
        LocalDateTime endTime = list.get(list.size()-1).getAddTime();
        return VehicleTrackStreamVO.of(startTime, endTime, list);
    }


    public List<StreamDataVO> vehicleStream(String park, String vno, LocalDateTime startDateTime, LocalDateTime endDateTime){

        ParkPGEntity parkEntity = NezhaPersonManager.getInstance().parkPGEntity(park);
        if (null == parkEntity || StrUtil.isEmpty(parkEntity.getStreamUrl())){
            log.error("historyStream handler>> park  null; park: {}", park);
            return null;
        }

        List<VehicleTrackRecordPGEntity> list = nezhaRecordService.listTrackRecord(park, vno, startDateTime, endDateTime);
        if (CollectionUtil.isEmpty(list)) {
            log.info("historyStream: history data is null, vno: {}", vno);
            return null;
        }

        list = list.stream().filter(v -> null != v.getActime() && v.getDoType() != 9).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(list)) {
            log.info("historyStream: history data is null, vno: {}", vno);
            return null;
        }

        List<VehicleTrackRecordPGEntity> tempList = new ArrayList<>();
        VehicleTrackRecordPGEntity temp = null;
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            VehicleTrackRecordPGEntity current = list.get(i);
            VehicleTrackRecordPGEntity next = list.get(i + 1);
            if (!current.getPoleCode().equals(next.getPoleCode())){
                if (temp == null || !current.getPoleCode().equals(temp.getPoleCode())){
                    tempList.add(current);
                }
                tempList.add(next);
                temp = next;
            }
        }

        if (temp == null || !list.get(size-1).getPoleCode().equals(temp.getPoleCode())){
            tempList.add(list.get(size-1));
        }

        AtomicInteger idGenerator = new AtomicInteger(0);
        List<StreamDataRequest> requestList = tempList.stream()
                .filter(t -> !(StrUtil.isEmpty(t.getCameraCode()) || null == t.getActime() || t.getActime() == 0L))
                .map(t -> {
                    String cno = t.getCameraCode();
                    Long aCtime = t.getActime();
                    long st = aCtime / 1000;
                    long et = st + 10;
                    return new StreamDataRequest(idGenerator.getAndIncrement(), cno, st, et);
                }).collect(Collectors.toList());



        List<StreamDataResponse> streamList = OkhttpUtil.pullStreamByList(requestList, parkEntity.getStreamUrl(), park);
        if (CollectionUtil.isEmpty(streamList)) {
            log.error("historyStream:  streamList is null");
            return new ArrayList<>();
        }

        streamList.sort(Comparator.comparing(StreamDataResponse::getStart_time));
        Map<Integer, StreamDataRequest> requestMap = requestList.stream().collect(Collectors.toMap(StreamDataRequest::getId, Function.identity()));
        Map<String, List<VehicleTrackRecordPGEntity>> map = tempList.stream().collect(Collectors.groupingBy(VehicleTrackRecordPGEntity::getCameraCode));

        return streamList.stream().map(s -> {
            String poleCode = Optional.ofNullable(map.get(s.getDevice_id())).map(l -> l.get(0)).map(VehicleTrackRecordPGEntity::getPoleCode).orElse(null);
            PolePGEntity pgEntity = StrUtil.isEmpty(poleCode) ? null : NezhaDeviceManager.getInstance().getPolePGEntityByPoleCode(park, poleCode);
            StreamDataVO streamDataVO = new StreamDataVO();
                    streamDataVO.setPath(s.getPath());
                    streamDataVO.setCno(s.getCno());
                    StreamDataRequest request = requestMap.get(s.getId());
                    streamDataVO.setStartTime(StringKits.timeSToString(request.getStart_time()));
                    streamDataVO.setEndTime(StringKits.timeSToString(request.getEnd_time()));
                    streamDataVO.setPoleCode(poleCode);
                    streamDataVO.setRoad(Optional.ofNullable(pgEntity).map(PolePGEntity::getRoad).orElse(""));
                    return streamDataVO;
        }).collect(Collectors.toList());

    }


    private List<StreamDataVO> pullStream(String park, VehicleTrackRecordPGEntity entity, String url){
        PolePGEntity pgEntity = NezhaDeviceManager.getInstance().getPolePGEntityByPoleCode(park, entity.getPoleCode());
        String cno = entity.getCameraCode();
        Long actime = entity.getActime();
        if (StrUtil.isEmpty(cno) || null == actime || actime == 0L){
            log.info("historyStream: park: {}, VehicleTrackRecord: {}", park, entity);
            return null;
        }
        long st = actime/1000;
        long et = st + 10;
        List<StreamDataResponse> list = OkhttpUtil.pullStream(cno, st, et, url, park);
        if (CollectionUtil.isEmpty(list)){
            return null;
        }

        return list.stream().map(s -> {
            StreamDataVO streamDataVO = new StreamDataVO();
            streamDataVO.setPath(s.getPath());

            streamDataVO.setCno(cno);
            streamDataVO.setStartTime(StringKits.timeSToString(st));
            streamDataVO.setEndTime(StringKits.timeSToString(et));
            streamDataVO.setPoleCode(entity.getPoleCode());
            streamDataVO.setRoad(Optional.ofNullable(pgEntity).map(PolePGEntity::getRoad).orElse(""));
            return streamDataVO;
        }).collect(Collectors.toList());

    }


}
